package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserItemVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @author liubo
 * @description 针对表【system_user(员工信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemUser>
        implements SystemUserService {

    @Autowired
    private SystemUserMapper systemUserMapper;
    @Override
    public void userPage(Page<SystemUserItemVo> page, SystemUserQueryVo queryVo) {
        baseMapper.userPage(page,queryVo);
    }

    @Override
    public Object SUById(Long id) {
        SystemUserItemVo systemUserItemVo =systemUserMapper.SUById(id);
        return null;
    }

    @Override
    public void SUsaveOrUpdate(SystemUser systemUser) {
        // 创建一个查询包装器，用于后续的查询条件构建
        LambdaQueryWrapper<SystemUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 根据用户名查询，条件为用户名相等
        lambdaQueryWrapper.eq(SystemUser::getUsername,systemUser.getUsername());
        // 根据用户ID查询，条件为用户ID不为空且与给定ID不相等
        lambdaQueryWrapper.ne(systemUser.getId()!=null, SystemUser::getId,systemUser.getId());
        // 使用构建的查询条件统计满足条件的记录数
        long count = count(lambdaQueryWrapper);
        // 如果计数大于0，表示存在相同用户名或相同ID的用户，抛出异常
        if(count>0){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_EXIST_ERROR);
        }
        // 如果用户ID不为空，即用户存在，则更新用户密码为MD5加密后的密码
        if(!ObjectUtils.isEmpty(systemUser.getId())){
            systemUser.setPassword(DigestUtils.md5Hex(systemUser.getPassword()));
        }
        // 保存或更新用户信息，根据用户ID是否为空来决定是新增还是修改
        saveOrUpdate(systemUser);
    }
}




